import dayjs from 'dayjs'
import config from '@/config/env'

function dayjsFunc(time) {
    let times = String(time).length == 10 ? time * 1000 : time;
    return dayjs(Number(times)).format("YYYY-MM-DD HH:mm:ss");
}

function throttle(fn, interval) {
    var enterTime = 0; //触发的时间
    var gapTime = interval || 2000; //间隔时间，如果interval不传，则默认300ms
    return function() {
        var context = this;
        var backTime = new Date(); //第一次函数return即触发的时间
        if (backTime - enterTime > gapTime) {
            fn.call(context, arguments);
            enterTime = backTime; //赋值给第一次触发的时间，这样就保存了第二次触发的时间
        }
    };
}
/*函数防抖*/
function debounce(fn, interval) {
    var timer;
    var gapTime = interval || 1000; //间隔时间，如果interval不传，则默认1000ms
    return function() {
        clearTimeout(timer);
        var context = this;
        var args = arguments; //保存此处的arguments，因为setTimeout是全局的，arguments不是防抖函数需要的。
        timer = setTimeout(function() {
            fn.call(context, args);
        }, gapTime);
    };
}

// 设置cookie
function setCookie(name, value, time, domain = config.domain) {
    let Days = time * 60 * 1000
    let exp = new Date()
    exp.setTime(exp.getTime() + Days)
    let a = name + '=' + encodeURIComponent(value) + ';path=/;domain=' + domain
    document.cookie = a
}
// 获取cookie
function getCookie(name) {
    let reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)')
    let arr = document.cookie.match(reg)
    if (arr) {
        return decodeURIComponent(arr[2])
    } else {
        return null
    }
}

// 删除cookie
function delCookie(name, domain = config.domain) {
    var exp = new Date()
    exp.setTime(exp.getTime() - 1)
    var cval = getCookie(name)
    if (cval !== null) {
        let ck = name + '=' + cval + ';expires=' + exp.toGMTString() + ';path=/;domain=' + domain
        document.cookie = ck
    }
}
// 将科学计数法转换为小数
function toNonExponential(num, digits = 4) {
    if (num) {
        num = Number(Number(num).toFixed(digits))
        var m = num.toExponential().match(/\d(?:\.(\d*))?e([+-]\d+)/)
        return num.toFixed(Math.max(0, (m[1] || '').length - m[2]))
    } else {
        return 0
    }
}

export default {
    dayjsFunc: dayjsFunc,
    throttle: throttle,
    debounce: debounce,
    setCookie: setCookie,
    getCookie: getCookie,
    delCookie: delCookie,
    toNonExponential: toNonExponential
}